package com.sdy.hospitalguard.web.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.common.model.BizException;
import com.sdy.common.model.Response;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.IdCardUtil;
import com.sdy.common.utils.StringUtil;
import com.sdy.hospitalguard.biz.dto.AddPatientEscortDTO;
import com.sdy.hospitalguard.biz.dto.EscortManageDTO;
import com.sdy.hospitalguard.biz.dto.SelectVisitDTO;
import com.sdy.hospitalguard.biz.dto.VisitManageDTO;
import com.sdy.hospitalguard.biz.model.HospitalUser;
import com.sdy.hospitalguard.biz.model.PatientInformation;
import com.sdy.hospitalguard.biz.service.*;
import com.sdy.hospitalguard.biz.utils.ParamChecker;
import com.sdy.hospitalguard.biz.utils.SearchBrowserKeywordsUtil;
import com.sdy.mvc.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author: 王越洋
 * @version: v1.0
 * @description: com.sdy.hospitalguard.web.controller
 * @date:2020/5/26
 */
@RestController
@RequestMapping("/escort")
@Api(tags = "陪护管理接口")
public class EscortManagementController extends BaseController {

    @Autowired
    private EscortAssociatedService escortAssociatedService;
    @Autowired
    private PatientInformationService patientInformationService;
    @Autowired
    private HospitalUserService hospitalUserService;
    @Autowired
    private ManagerService managerService;

    @GetMapping("/escortPageQuery")
    @ApiOperation(value = "陪护者分页查询")
    public Response escortPageQuery(String message, Integer areaId, String start, String end, Page page, HttpServletRequest request) throws Exception{
        Integer userId = getUserId(request);
        Integer roleId = managerService.getById(userId).getRoleId();
        if (roleId == 2 || roleId == 4) {
            return Response.error("当前用户不显示此界面!");
        }
        Integer userAreaId = managerService.getById(userId).getInpatientAreaId();
        if (StringUtil.isBlank(message)) {
            message = null;
        } else {
            message = URLDecoder.decode(message, "UTF-8");
        }
        if (StringUtil.isBlank(start) || StringUtil.isBlank(end)) {
            start = null;
            end = null;
        }
        if (StringUtil.isNotBlank(start)) {
            start = URLDecoder.decode(start, "UTF-8");
        }
        if (StringUtil.isNotBlank(end)) {
            end = URLDecoder.decode(end, "UTF-8");
        }
        IPage<EscortManageDTO> escortManageDTOIPage = escortAssociatedService.getEscortInformation(page, message, areaId, start, end, userAreaId);
        List<EscortManageDTO> escortManageDTOList = escortManageDTOIPage.getRecords();
        for (int i=0; i<escortManageDTOList.size(); i++) {
            String phone = escortManageDTOList.get(i).getEscortPhone();
            escortManageDTOList.get(i).setEscortPhone(phone.substring(0, 3) + "****" +
                    phone.substring(7));
        }
        return Response.success(escortManageDTOIPage);
    }

    @GetMapping("/excelExport")
    @ApiOperation(value = "陪护者Excel导出")
    public void excelExport(String message, Integer areaId, String start, String end,
                            HttpServletRequest request, HttpServletResponse response) throws IOException {
        Integer userId = getUserId(request);
        Integer roleId = managerService.getById(userId).getRoleId();
        if (roleId == 2 || roleId == 4) {
            new Throwable("当前用户不显示此界面!");
            return;
        }
        Integer userAreaId = managerService.getById(userId).getInpatientAreaId();
        if (StringUtil.isBlank(message)) {
            message = null;
        } else {
            message = URLDecoder.decode(message, "UTF-8");
        }
        if (StringUtil.isBlank(start) || StringUtil.isBlank(end)) {
            start = null;
            end = null;
        }
        if (StringUtil.isNotBlank(start)) {
            start = URLDecoder.decode(start, "UTF-8");
        }
        if (StringUtil.isNotBlank(end)) {
            end = URLDecoder.decode(end, "UTF-8");
        }
        List<EscortManageDTO> escortManageDTOList = escortAssociatedService.getEscortInformationList(message, areaId, start, end, userAreaId);
        for (int i=0; i<escortManageDTOList.size(); i++) {
            String phone = escortManageDTOList.get(i).getEscortPhone();
            escortManageDTOList.get(i).setEscortPhone(phone.substring(0, 3) + "****" +
                    phone.substring(7));
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String datetime = sdf.format(new Date());
        String fileName = datetime + "陪护记录.xlsx";
        boolean isMSIE = SearchBrowserKeywordsUtil.isMSBrowser(request);
        if (isMSIE) {
            /**
             * IE、360兼容版浏览器的乱码问题解决
             */
            fileName = URLEncoder.encode(fileName , "UTF-8");
        } else {
            /**
             *万能乱码问题解决
             */
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        EasyExcel.write(response.getOutputStream(), EscortManageDTO.class).sheet("陪护记录").doWrite(escortManageDTOList);
    }

    @GetMapping("/updEscortType")
    @ApiOperation(value = "陪护者状态修改")
    public Response updEscortType(Integer id, HttpServletRequest request){
        Integer userId = getUserId(request);
        Integer roleId = managerService.getById(userId).getRoleId();
        if (roleId == 2 || roleId == 4) {
            return Response.error("当前用户不显示此界面!");
        }
        return Response.success("");
    }

    @PostMapping("/saveEscort")
    @ApiOperation(value = "新增患者陪护")
    public Response saveEscort(@RequestBody AddPatientEscortDTO addPatientEscortDTO, HttpServletRequest request) throws BizException{
        Integer userId = getUserId(request);
        Integer roleId = managerService.getById(userId).getRoleId();
        if (roleId == 2 || roleId == 4) {
            return Response.error("当前用户不显示此界面!");
        }
        String admissionNumber = addPatientEscortDTO.getAdmissionNumber();
        Integer sickbedId = addPatientEscortDTO.getSickbedId();
        String name = addPatientEscortDTO.getName();
        String cardId = addPatientEscortDTO.getCardId();
        String phone = addPatientEscortDTO.getPhone();
        Assert.isBlank(admissionNumber, "住院号不能为空!");
        Assert.isNull(sickbedId, "床位号不能为空!");
        Assert.isTrue(!ParamChecker.checkParamRequired(name), "参数<姓名>不能为空!");
        Assert.isTrue(!ParamChecker.checkParamRequired(cardId), "参数<身份证号>不能为空!");
        Assert.isTrue(!IdCardUtil.IDCardValidate(cardId).equals("true"), "身份证号格式错误!");
        Assert.isTrue(!ParamChecker.checkParamRequired(phone), "参数<手机号>不能为空!");
        Assert.isTrue(!phone.matches(com.sdy.common.constant.Constants.REGEX_PHONE), "手机号格式错误!");
        LambdaQueryWrapper<HospitalUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HospitalUser::getName, name);
        queryWrapper.eq(HospitalUser::getIdCard, cardId);
        queryWrapper.eq(HospitalUser::getPhone, phone);
        HospitalUser hospitalUser = hospitalUserService.getOne(queryWrapper);
        if (hospitalUser == null) {
            return Response.error("无此陪护用户!");
        }
        LambdaQueryWrapper<PatientInformation> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PatientInformation::getAdmissionNumber, admissionNumber);
        lambdaQueryWrapper.eq(PatientInformation::getSickbedId, sickbedId);
        lambdaQueryWrapper.eq(PatientInformation::getPatientState, 0);
        PatientInformation patientInformation = patientInformationService.getOne(lambdaQueryWrapper);
        if (patientInformation == null) {
            return Response.error("无此住院信息或已出院!");
        }
        escortAssociatedService.saveEscort(hospitalUser.getId(), patientInformation.getId());
        return Response.success("");
    }

}
